#coding=utf-8
from django.db import models
from fundamental import TradabelShare
import scraper
from stvalidator import *
from stutils import float2dec,data2csv
import datetime
td = datetime.date.today().isoformat()

class Stcode(models.Model):
    
    '''stcode用于记录 、更新stock代码(code)和名称(name)。
    当新股发行or原有股票更改名称后，数据表中就增加条记录。'''
    
    code = models.CharField(max_length=6)
    name = models.CharField(max_length=20)
    created_at = models.DateField(auto_now_add=True)
    
    class Admin:pass
    class Meta:
        app_label = 'shstock'
        
    def __unicode__(self):
        return "%s(%s)"%(self.name, self.code)
    
class Tag(models.Model):
    name = models.CharField(max_length=100)
    class Admin:pass
    class Meta:
        app_label = 'shstock'    
    def __unicode__(self):
        return self.name
        
class Share(models.Model):
    code = models.CharField(max_length=6, unique=True)
    name = models.CharField(max_length=20)
    ipo = models.DateField()
    
    tags = models.ManyToManyField(Tag, null=True,blank=True)

    class Admin:pass
    class Meta:
        app_label = 'shstock'
    
    def __unicode__(self):
        return "%s(%s)"%(self.name, self.code)
        
    def histprice2db(self):    
        
        head = ["日期", "开盘价",	"最高价", "收盘价", "最低价","交易量(手)", "交易金额(万元)"]
        data = scraper.get_histprice(self.code, self.ipo)
        
        #put data into csv file
        fn= '%s/%s.csv'%(HISTPRICEDIR , self.code)
        data2csv(data, head, fn)
        
        #validation
        for d in data:
            isValidPricefromSina(d)

        #data 2 db
        pre = None
        for d in data:
            e = Exday(share=self, date=d[0])   
            if pre: e.pre = pre
            e.save()
            pre = e
            
            v = int(Decimal( d[5] ) * 100 )
            a = int(Decimal( d[6] ) * 10000 )
            
            dd = [float2dec(i, 2) for i in d[1:5]]
            p = Price(exday=e, start=dd[0], high=dd[1], end=dd[2], low=dd[3], volume=v, amount=a )
            p.save()
            
    def exday_today(self):
        '''get 日期是今日的交易日 object;'''
        try:
            e = self.exday_set.get(date=td)
        except Exday.DoesNotExist:
            return None
        return e
                
    def has_tdprice(self):
        e = self.exday_today()
        if not e:return False
        if e.price:
            return True
        return False
        
    def tdprice2db(self):
        '''当日price数据入库，如果当天没有交易 raise NoPriceTodayError'''
        td = datetime.date.today().isoformat()
        if self.has_tdprice():
            #print self, "price data(%s) is alread in database."%td
            return
            
        data = scraper.get_tdprice(self.code)
        #print data
        isValidPricefromSina(data)
        
        try:
            e = self.exday_set.get(date=data[0])
        except Exday.DoesNotExist:
            
            e = Exday(share=self, date=data[0])
            try:
                pre = self.exday_set.latest('date')
            except Exday.DoesNotExist:
                pre = None
            if pre: e.pre = pre
            e.save()
        
        d = data
        v = int(Decimal( d[5] ) * 100 )
        a = int(Decimal( d[6] ) * 10000 )
        
        dd = [float2dec(i, 2) for i in d[1:5]]
        p = Price(exday=e, start=dd[0], high=dd[1], end=dd[2], low=dd[3], volume=v, amount=a )
        p.save()

    def ts2db(self):
        '''get 该股流通A股数量'''
        i = 1
        while True:
            i = i + 1
            data = scraper.get_ts(self.code)
            if data:break
            if i > 20:
                print "Can not get 流通A股数量of%s"%self.code
                return
            sleep(0.1)
            
        for d in data:
            isValidDate(d[0])
    
        for d in data:
            q = int(d[1])
        
            if q <= 0:
                raise NegativeTSError(self.code)
            
            #check 是否数据已经存在
            try:
                self.tradableshare_set.get(date=d[0])
            except TradableShare.DoesNotExist,e:
                t = TradableShare(share=self, date=d[0], quantity=int(d[1]))
                t.save()

    def get_ts(self, date=None):
        if not date:
            return self.tradableshare_set.latest('date').quantity
        
        for t in self.tradableshare_set.all().order_by('-date'):
            if date >= t.date.isoformat():
                return t.quantity                
    ts = property(fget=get_ts)
